package cn.zhiyuan.yours.controller;

import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.Base64Kit;

import cn.zhiyuan.yours.model.User;

public class UserController extends Controller {
	private User user = new User();

	public void index() {
		List<User> userlist = null;
		userlist = this.user.find("select * from `user`");
		user = this.getSessionAttr("usersession");
		this.setAttr("userrole", user.getInt("role"));
		this.setAttr("userlist", userlist);
		this.render("user.html");
	}

	public void add() {
		this.render("add.html");
	}

	public void save() {
		User olduser = new User();
		user = this.user.set("user", this.getPara("user")).set("email", this.getPara("email"))
				.set("name", this.getPara("name")).set("sex", this.getPara("sex"))
				.set("password", Base64Kit.encode("123456"));
		olduser = this.user.findFirst("select * from `user` where `user` = '" + this.getPara("user")
				+ "' or `email` = '" + this.getPara("email") + "'");
		if (olduser == null) {
			user.save();
			this.redirect("/admin#user");
		} else {
			this.renderHtml(
					"<script> alert('用户名或者邮箱已存在，增加用户失败！');  window.location.href='/yours/admin#user'; </script>");
			// this.redirect("/admin#user");
		}

	}

	public void edit() {
		user = this.user.findFirst("select * from `user` where `id` = " + this.getPara(0));
		this.setAttr("user", user);
		this.render("edit.html");
	}

	public void update() {
		user = this.user.set("id", this.getPara(0)).set("user", this.getPara("user"))
				.set("email", this.getPara("email")).set("name", this.getPara("name")).set("sex", this.getPara("sex"));
		User olduser = new User();
		olduser = this.user.findFirst("select * from `user` where `user` = '" + this.getPara("user")
				+ "' or `email` = '" + this.getPara("email") + "'");
		if (olduser == null) {
			user.update();
			this.redirect("/admin#user");
		} else {
			this.renderHtml(
					"<script> alert('用户名或者邮箱已存在，更新用户失败！');  window.location.href='/yours/admin#user'; </script>");

		}

	}

}
